package com.caiwangdai.app.ui.borrow

import android.content.Context
import android.content.Intent
import android.support.v4.content.ContextCompat
import android.text.TextPaint
import android.view.View
import android.widget.AdapterView
import com.caiwangdai.app.BuildConfig
import com.caiwangdai.app.R
import com.caiwangdai.app.backend.RetrofitHome
import com.caiwangdai.app.backend.observer.OnDataV2Listener
import com.caiwangdai.app.backend.rx.RxSchedulers
import com.caiwangdai.app.bean.LoanApplicationB
import com.caiwangdai.app.bean.LoanProductB
import com.caiwangdai.app.bean.LoanProductPoolB
import com.caiwangdai.app.bean.base.NormalResponseB
import com.caiwangdai.app.extension.*
import com.caiwangdai.app.origin.BaseActivity
import com.caiwangdai.app.origin.ToolBarManager
import com.caiwangdai.app.origin.web.NormalWebActivity
import com.caiwangdai.app.ui.borrow.adapter.BorrowIntentAdapter
import com.caiwangdai.app.ui.verify.FaceVerifyReadyActivity
import com.caiwangdai.app.ui.verify.IDCardInfoActivity
import com.caiwangdai.app.ui.verify.RealNameVerifyActivity
import com.caiwangdai.app.ui.verify.VerifyResultActivity
import com.orhanobut.logger.Logger
import kotlinx.android.synthetic.main.activity_borrow_intention.*

//借款意向
class BorrowIntentionActivity : BaseActivity() {
    override fun getLayoutResID() = R.layout.activity_borrow_intention

    var isAgreeProtocol = true
    var amount = -1
    var days = -1
    var currentProduct: LoanProductB? = null

    val productTypeList = mutableListOf<String>()
    val productList = mutableListOf<List<LoanProductB>>()

    var isVerifySuccess: Boolean = false


    companion object {
        val VERIFY_SUCCESS = "verify_success"

        fun newInstance(context: Context, isVerifySuccess: Boolean = false): Intent {
            val intent = Intent(context, BorrowIntentionActivity::class.java)
            intent.putExtra(VERIFY_SUCCESS, isVerifySuccess)
            return intent
        }
    }


    override fun initData() {
        //获取信息
        getLoanProduct()
    }

    override fun onLoginSuccess() {
        //获取信息
        getLoanProduct()
    }

    override fun onLoginCancel() {
        onBackPressed()
    }

    override fun initView() {
        //toolbar
        ToolBarManager.with(this, WMContent)
                .setTitle("借款意向")
                .setNavigationIcon(R.drawable.ic_nav_arrow_white)


        //wonder 综合费用
        tv_wonder.setOnClickListenerPro {
            showComprehensiveFeeDialog(currentProduct!!)
        }

        //protocol
        cb_protocol.isChecked = isAgreeProtocol
        tv_protocol.dyeWithClick(7, tv_protocol.length(), R.color.colorPrimary, ClickSpan())

        //btn-submit
        btn_borrow.setOnClickListenerPro {
            if (CheckAllOperation()) applyLoan()
        }

    }


    //认证成功后
    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        Logger.e("onNewIntent")
        isVerifySuccess = intent?.getBooleanExtra(VERIFY_SUCCESS, false)!!
        if (isVerifySuccess) applyLoan()
    }

    //获取贷款产品
    private fun getLoanProduct() {
        RetrofitHome.getHomeApi()
                .getLoadProduct()
                .compose(RxSchedulers.toMain())
                .subscribe(object : OnDataV2Listener<LoanProductPoolB>(this, swipe_refresh, true) {

                    override fun onSuccess(value: NormalResponseB<LoanProductPoolB>) {
                        filterLoan(value.data!!)
                    }
                })
    }


    private fun filterLoan(result: LoanProductPoolB) {
        val product = result.product
        productTypeList.addAll(result.product_type!!)
        for ((index, item) in productTypeList.withIndex()) {
            val cut = product!!.filter { it.amount == item }
            productList.add(cut)
        }
        initSpinnerMoney()

    }

    //money
    private fun initSpinnerMoney() {
        //spinner money
        val moneyData = mutableListOf<String>()
//        moneyData.add("请选择借款数额")
        for (item in productTypeList) {
            moneyData.add(item + "元")
        }
        val moneyAdapter = BorrowIntentAdapter(this, moneyData)
        spinner_borrow_money.adapter = moneyAdapter
        spinner_borrow_money.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onNothingSelected(parent: AdapterView<*>?) {
            }

            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                val str = parent?.getItemAtPosition(position).toString()
                amount = position
                initSpinnerDays(position)
            }

        }
    }

    //day
    private fun initSpinnerDays(position: Int) {
        //spinner day
        val DayData = mutableListOf<String>()
//        DayData.add("请选择借款期限")
        for (item in productList[position]) {
            DayData.add("${item.days}天")
        }
        val dayAdapter = BorrowIntentAdapter(this, DayData)
        spinner_borrow_day.adapter = dayAdapter
        spinner_borrow_day.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onNothingSelected(parent: AdapterView<*>?) {
            }

            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                days = position
                selectLoanProduct()
            }

        }
    }

    private fun selectLoanProduct() {
        currentProduct = productList[amount][days]
        //借款金额
        tv_total_fee.text = currentProduct?.acc_money + "元"

        //综合费用
        tv_loan_money.text = currentProduct?.all_fee + "元"
    }


    inner class ClickSpan : BaseClickSpan() {
        override fun onClick(widget: View?) {
            startActivity(NormalWebActivity.newInstance(mContext, BuildConfig.HOST + "/pages/loan_agreement.html", "借款协议"))
        }

        override fun updateDrawState(ds: TextPaint?) {
            super.updateDrawState(ds)
            ds?.color = ContextCompat.getColor(mContext, R.color.colorPrimary)
        }

    }


    private fun CheckAllOperation(): Boolean {
        isAgreeProtocol = cb_protocol.isChecked
        if (!isAgreeProtocol) {
            toast("请阅读《贷款协议》")
            return false
        }
        if (amount == -1) {
            toast("请选择借款金额")
            return false
        }
        if (days == -1) {
            toast("请选择借款期限")
            return false
        }
        return true
    }

    fun applyLoan() {
        val productID = productList[amount][days].id
        RetrofitHome.getHomeApi()
                .applyForLoan(productID)
                .compose(RxSchedulers.toMain())
                .subscribe(object : OnDataV2Listener<LoanApplicationB>(this) {
                    override fun getProgressBarContent() = "申请中..."

                    override fun onSuccess(value: NormalResponseB<LoanApplicationB>) {
                        dispatchPages(value.data!!)
                    }

                    override fun onFail(message: String?) {
                        //todo 以后还得测试SurfaceView的问题
//                        startActivity(IDCardInfoActivity.newInstance(mContext))
                        startActivity(VerifyResultActivity.newInstance(mContext, false, message!!))
                    }
                })
    }

    private fun dispatchPages(loanData: LoanApplicationB) {
        when (loanData.authStatus) {
            0 -> {
                //借款成功
                startActivity(VerifyResultActivity.newInstance(mContext, true, "申请成功，等待审核"))
            }
            1 -> {
                //身份证
                startActivity(IDCardInfoActivity.newInstance(mContext))
            }
            2 -> {
                //人脸
                startActivity(FaceVerifyReadyActivity.newInstance(mContext))
                overridePendingTransition(R.anim.slide_in_from_bottom, -1);
            }
            3 -> {
                //银行卡
                startActivity(RealNameVerifyActivity.newInstance(mContext))
            }
        }
    }


}
